<template>
  <div v-if="product">
    <el-card :body-style="{ padding: '20px' }">
      <div slot="header" class="clearfix">
        <span class="product-detail-header">商品详情</span>
      </div>

      <div class="product-detail">
        <img :src="product.image" alt="product image" class="product-image" />
        <div class="product-info">
          <h2>{{ product.name }}</h2>
          <p><strong>价格:</strong> ¥{{ product.price }}</p>
          <p><strong>描述:</strong> {{ product.detail }}</p>
          <p v-if="product.category"><strong>分类:</strong> {{ product.category }}</p>

          <!-- 显示平均评分 -->
          <div class="average-score">
            <span>平均得分:</span>
            <div class="star-rating">
              <span
                v-for="index in 5"
                :key="index"
                :class="{'star-filled': index <= averageScore, 'star-empty': index > averageScore}"
              >
                ★
              </span>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 评论区 -->
    <el-card :body-style="{ padding: '20px' }" class="comment-section">
      <div slot="header" class="clearfix">
        <span class="product-detail-header">用户评论</span>
      </div>

      <div v-if="comments.length > 0">
        <div v-for="comment in comments" :key="comment.id" class="comment-item">
          <div class="comment-header">
            <span class="comment-person">{{ comment.person }}</span>
            <div class="star-rating">
              <!-- 渲染评论的评分星星 -->
              <span
                v-for="index in 5"
                :key="index"
                :class="{'star-filled': index <= comment.score, 'star-empty': index > comment.score}"
              >
                ★
              </span>
            </div>
            <span class="comment-time">{{ comment.timestamp }}</span>
          </div>
          <p class="comment-content">{{ comment.comment }}</p>
        </div>
      </div>
      <div v-else>
        <p>暂无评论</p>
      </div>

      <!-- 评论表单 -->
      <el-form :model="newComment" @submit.prevent="submitComment">
        <el-form-item label="选择评分" :label-width="'100px'">
          <div class="star-rating">
            <span
              v-for="index in 5"
              :key="index"
              :class="{'star-filled': index <= score, 'star-empty': index > score}"
              @click="selectScore(index)"
            >
              ★
            </span>
          </div>
        </el-form-item>

        <el-form-item label="添加评论" :label-width="'100px'">
          <el-input
            v-model="newComment.content"
            type="textarea"
            placeholder="请输入您的评论"
            rows="4"
          />
        </el-form-item>
        <el-button type="primary" @click="submitComment">提交评论</el-button>
      </el-form>
    </el-card>
  </div>

  <div v-else>
    <el-spinner size="large" />
  </div>
</template>

<script>
export default {
  name: 'ProductDetail',
  data() {
    return {
      product: null,
      comments: [], // 存储评论
      averageScore: 0, // 存储平均评分
      score: 0, // 存储选择的评分
      newComment: { content: '' }, // 存储新评论
    };
  },
  created() {
    this.fetchProductDetail();
    this.fetchProductComments();
  },
  methods: {
    fetchProductDetail() {
      const productId = this.$route.params.id;
      this.$http.get(`product/detail`, { params: { id: productId } })
        .then(res => {
          if (res.data.code === 1) {
            this.product = res.data.data;
          } else {
            this.$message.error(res.data.msg || '加载商品详情失败');
          }
        })
        .catch(err => {
          console.error('Failed to load product details:', err);
          this.$message.error('加载商品详情失败');
        });
    },

    fetchProductComments() {
      const productId = this.$route.params.id;
      this.$http.get(`product/score/${productId}`)
        .then(res => {
          if (res.data.code === 1) {
            this.comments = res.data.data; // 假设返回的评论数据存储在 data 中
            this.calculateAverageScore(); // 计算平均评分
          } else {
            this.$message.error(res.data.msg || '加载评论失败');
          }
        })
        .catch(err => {
          console.error('Failed to load comments:', err);
          this.$message.error('加载评论失败');
        });
    },

    calculateAverageScore() {
      if (this.comments.length > 0) {
        const totalScore = this.comments.reduce((acc, comment) => acc + comment.score, 0);
        this.averageScore = (totalScore / this.comments.length).toFixed(1); // 保留1位小数
      }
    },

    selectScore(index) {
      this.score = index; // 更新选择的评分
    },

    submitComment() {
      // 获取产品ID和评论内容
      const productId = this.$route.params.id;
      const comment = this.newComment.content.trim();

      // 验证评论内容和评分
      if (!comment) {
        this.$message.warning('评论内容不能为空');
        return;
      }

      if (this.score === 0) {
        this.$message.warning('请选择评分');
        return;
      }

      // 显示加载提示
      const loading = this.$loading({
        lock: true,
        text: '提交中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      });

      // 发送 POST 请求提交评论
      this.$http.post('product/inscore', {
        id: productId,
        score: this.score,
        comment: comment,
      })
        .then(response => {
          // 请求完成后关闭加载提示
          loading.close();

          if (response.data.code === 401) {
            // 如果返回未授权，提示用户登录
            this.$message.error('请先登录');
            return;
          }

          // 如果提交成功
          if (response.data.code === 1) {
            const newCommentData = response.data.data;

            // 新评论推送到评论数组
            this.comments.push({
              person: newCommentData.person, // 使用返回的 person 字段
              comment: newCommentData.comment,
              timestamp: new Date().toLocaleString(),
              id: newCommentData.id, // 使用返回的评论ID
              score: newCommentData.score,
            });

            // 重新计算平均评分
            this.calculateAverageScore();

            // 清空评论输入框和评分
            this.newComment.content = '';
            this.score = 0;

            // 显示成功消息
            this.$message.success('评论提交成功');
          } else {
            // 请求失败时处理错误
            this.$message.error(`评论提交失败: ${response.data.msg || '未知错误'}`);
          }
        })
        .catch(error => {
          // 请求失败时关闭加载提示，并显示错误
          loading.close();
          console.error('评论提交失败:', error);
          this.$message.error('评论提交失败');
        });
    }
  },
};
</script>

<style scoped>
/* 样式保持不变 */
.product-detail {
  display: flex;
  gap: 20px;
}

.product-image {
  width: 300px;
  height: 300px;
  object-fit: cover;
}

.product-info {
  max-width: 600px;
}

.product-detail-header {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.el-spinner {
  display: flex;
  justify-content: center;
  margin-top: 50px;
}

.comment-section {
  margin-top: 40px;
}

.comment-item {
  padding: 10px;
  border-bottom: 1px solid #eee;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.comment-person {
  font-weight: bold;
}

.comment-time {
  font-size: 12px;
  color: #888;
}

.star-rating {
  display: inline-block;
}

.star-filled {
  color: gold;
}

.star-empty {
  color: lightgray;
}

.comment-content {
  margin-top: 10px;
  font-size: 14px;
  color: #555;
}

.el-form-item {
  margin-bottom: 20px;
}

.average-score {
  margin-top: 20px;
}

.average-score span {
  margin-right: 10px;
}
</style>
